<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Validate;
class User extends Allow
{	
	//显示查询到的用户
    public function getIndex()
    {
        $req = Request();
        //paginate  分页     where  条件查询
        $userinfo = Db::table('admin_user')->where('username','like',"%".$req->param('name')."%")->paginate(5);
        //发送参数分别是   查询好的信息    查询url信息在模板页面使用appends来接受   接受查询的关键字
        return $this->fetch("user/index",['info'=>$userinfo,'req'=>$req->param(),'k'=>$req->param('name')]);

    }


    //删除用户
    public function getDel(){
    	$req = Request();
    	$id=$req->param('id');
    	$info = Db::table('admin_user')->where('id',$id)->delete();
    	if ($info) {
    		$this->success('删除成功','/user/index');
    	}else{
    		$this->success('删除失败','/user/index');
    	}
    }

    //增加用户
    public function getAdd(){
        return $this->fetch("/user/add");
    }

    public function postInsert(){
    	// V($_POST);
    	$req = Request();
    	$data['username']=$req->param('username');
    	$data['email']=$req->param('email');
    	$data['pass']=md5($req->param('pass'));
    	$data['auth']=1;
    	$data['status']=$req->param('status');
    	$data['addtime']=date('Y-m-d H:i:s',time());
    	// V($data);
    	//定义规则
    	$rule = [
			'username' => 'require|max:25',
			'email' => 'require|email',
			'pass'=>'require|min:6|max:16',
			'repass'=>'require|min:6|max:16'
			];

		//定义提示消息
		$msg = [
			'username.require' => '名称必须',
			'username.max' => '名称最多不能超过25个字符',
			'email.require' => '邮箱不能为空',
			'email' => '邮箱格式错误',
			'pass.require' => '请输入密码',
			'pass.min' => '密码最少6位',
			'pass.max' => '密码不得超过16位',
			'repass.require' => '请确认密码'

			];
    	$validate = new Validate($rule, $msg);
    	$result = $validate->batch()->check($_POST);
    	if (!$result) {
	    	V($validate->getError());

    	}else{
    		if (($req->param('pass'))==($req->param('repass'))) {
    			if(DB::table('admin_user')->insert($data)){
    				$this->success('添加成功','/user/index');
    			}else{
    				$this->error('添加失败','/user/add');
    			}
    		}else{
    			$this->error('两次密码不一致','/user/add');
    		}
    	}

    }


    //修改数据
    public function getEdit($id){
    	$userinfo = Db::table('admin_user')->where('id','=',$id)->select();

    	return $this->fetch('user/edit',['userinfo'=>$userinfo]);
    }


    public function postUpdate(){
    	$req = Request();
		$id = $req->param('id');
		// $data['username'] = $req->param('username');
		$data['email'] = $req->param('email');
		$data['pass'] = md5($req->param('pass'));
		$data['status'] = $req->param('status');
		if (Db::table('admin_user')->where('id',$id)->update($data)) {
			Sql('admin_user');
			$this->success('修改成功','/user/index');
		}

    }

}
